/**
 * 展示模块
 * @author holyhigh
 */
const C_E_MAP: any = {
  ' ': '&nbsp;',
  '!': '&excl;',
  '"': '&quot;',
  '#': '&num;',
  $: '&dollar;',
  '%': '&percnt;',
  '&': '&amp;',
  "'": '&apos;',
  '(': '&lpar;',
  ')': '&rpar;',
  '*': '&ast;',
  '+': '&plus;',
  ',': '&comma;',
  '-': '&hyphen;',
  '.': '&period;',
  '/': '&sol;',
  ':': '&colon;',
  ';': '&semi;',
  '<': '&lt;',
  '=': '&equals;',
  '>': '&gt;',
  '?': '&quest;',
  '@': '&commat;',
  '[': '&lsqb;',
  '\\': '&bsol;',
  ']': '&rsqb;',
  '^': '&circ;',
  _: '&lowbar;',
  '`': '&grave;',
  '{': '&lcub;',
  '|': '&verbar;',
  '}': '&rcub;',
  '~': '&tilde;',
}

const E_C_MAP: any = {}
for (let k in C_E_MAP) {
  E_C_MAP[C_E_MAP[k]] = k
}

/**
 * 转换数字金额到汉字大写金额
 * @param {string | number} money 需要转换的数字，最大不能超过 999999999999999.9999
 * @return {string} 如果超过最大限制，返回###
 */
function numberToChinese(money: string | number): string {
  // 汉字的数字
  const cnNums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
  // 基本单位
  const cnIntRadice = ['', '拾', '佰', '仟']
  // 对应整数部分扩展单位
  const cnIntUnits = ['', '万', '亿', '兆']
  // 对应小数部分单位
  const cnDecUnits = ['角', '分', '毫', '厘']
  // 整数金额时后面跟的字符
  const cnInteger = '整'
  // 整型完以后的单位
  const cnIntLast = '元'

  // 最大处理的数字
  const maxNum = 999999999999999.9999
  // 金额整数部分
  let integerNum
  // 金额小数部分
  let decimalNum
  // 输出的中文金额字符串
  let chineseStr = ''
  // 分离金额后用的数组，预定义
  let parts
  if (money === '') {
    return ''
  }

  money = parseFloat(money + '')
  if (money >= maxNum) {
    return '###'
  }
  if (money === 0) {
    chineseStr = cnNums[0] + cnIntLast + cnInteger
    return chineseStr
  }

  money = money.toString()
  if (money.indexOf('.') === -1) {
    integerNum = money
    decimalNum = ''
  } else {
    parts = money.split('.')
    integerNum = parts[0]
    decimalNum = parts[1].substr(0, 4)
  }
  let integer = parseInt(integerNum, 10)
  if (integer < 0) {
    integer *= -1
    integerNum = integer + ''
  }
  // 获取整型部分转换
  if (integer > 0) {
    var zeroCount = 0
    var IntLen = integerNum.length
    for (var i = 0; i < IntLen; i++) {
      var n = integerNum.substr(i, 1)
      var p = IntLen - i - 1
      var q = p / 4
      var m = p % 4
      if (n === '0') {
        zeroCount++
      } else {
        if (zeroCount > 0) {
          chineseStr += cnNums[0]
        }
        // 归零
        zeroCount = 0
        chineseStr += cnNums[parseInt(n)] + cnIntRadice[m]
      }
      if (m === 0 && zeroCount < 4) {
        chineseStr += cnIntUnits[q]
      }
    }
    chineseStr += cnIntLast
  }
  // 小数部分
  if (decimalNum !== '') {
    const decLen = decimalNum.length
    for (let i = 0; i < decLen; i++) {
      const n = decimalNum.substr(i, 1)
      if (n !== '0') {
        chineseStr += cnNums[Number(n)] + cnDecUnits[i]
      }
    }
  }
  if (chineseStr === '') {
    chineseStr += cnNums[0] + cnIntLast + cnInteger
  } else if (decimalNum === '') {
    chineseStr += cnInteger
  }
  return chineseStr
}

/**
 * 转换rgb颜色并返回hex字符串
 * @param {string | Array<number|string>} rgbColor 符合dom规则的rgb字符串或rgb颜色数组
 * @return {string} 16进制颜色字符串
 */
function rgbToHex(rgbColor: string | Array<number | string>): string {
  let r, g, b
  if (typeof rgbColor === 'string') {
    const matcher =
      /rgb\(\s*(?<r>\d{1,3})\s*(?:,|\s)\s*(?<g>\d{1,3})\s*(?:,|\s)\s*(?<b>\d{1,3})\s*\)/.exec(
        rgbColor
      )
    if (matcher) {
      r = (matcher as any).groups.r
      g = (matcher as any).groups.g
      b = (matcher as any).groups.b
    }
  } else {
    r = rgbColor[0]
    g = rgbColor[1]
    b = rgbColor[2]
  }
  r = parseInt(r as string) || 0
  g = parseInt(g as string) || 0
  b = parseInt(b as string) || 0
  r = r > 255 ? 255 : r < 0 ? 0 : r
  g = g > 255 ? 255 : g < 0 ? 0 : g
  b = b > 255 ? 255 : b < 0 ? 0 : b
  return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)
}

/**
 * 16进制颜色转rgb并返回rgb颜色字符串
 * @param {number|string} hexColor 带#的字符串或16进制数字
 * @return {string} rgb颜色字符串
 */
function hexToRgb(hexColor: number | string): string {
  if (typeof hexColor === 'string') {
    hexColor = parseInt(hexColor.replace('#', ''), 16) || 0
  }
  return `rgb(${(0xff0000 & hexColor) >> 16},${(0xff00 & hexColor) >> 8},${
    0xff & hexColor
  })`
}

/**
 * 16进制颜色转rgb并返回rgb颜色数组
 * @param {number|string} hexColor 带#的字符串或16进制数字
 * @return {Array<number>} rgb颜色数组
 */
function hexToRgbAry(hexColor: number | string): Array<number> {
  if (typeof hexColor === 'string') {
    hexColor = parseInt(hexColor.replace('#', '')) || 0
  }
  return [
    (0xff0000 & hexColor) >> 16,
    (0xff00 & hexColor) >> 8,
    0xff & hexColor,
  ]
}

/**
 * 转义字符串中的html实体
 * @param {string} str
 * @return {string} 转义后的字符串
 */
function escapeEntity(str: string): string {
  return str.replace(/\D{1}/g, (c: string) => C_E_MAP[c] || c)
}

/**
 * 反转义字符串中的html实体
 * @param {string} str
 * @return {string} 转义后的字符串
 */
function unescapeEntity(str: string): string {
  return str.replace(/&[a-z]+?;/g, (c: string) => E_C_MAP[c] || c)
}

/**
 * 从身份证号码中获取签发地(编码)、生日、性别
 * @param {string} idStr 身份证号码
 * @return {object} 空对象或包含place/date/sex信息的对象
 */
function getIdInfo(idStr: string):
  | {}
  | {
      place: string
      date: string
      sex: string
    } {
  const matcher = (idStr || '').match(
    /^(?<place>\d{6})(?<date>(?:19|20)\d{6})\d{2}(?<sex>[0-9])[0-9a-zA-Z]$/
  )
  const groups = matcher?.groups
  if (!groups) return {}
  const date = groups.date + ''
  return {
    place: groups.place,
    date:
      date.substring(0, 4) +
      '-' +
      date.substring(4, 6) +
      '-' +
      date.substring(6, 8),
    sex: parseInt(groups.sex) % 2 === 0 ? 'f' : 'm',
  }
}

export {
  numberToChinese,
  rgbToHex,
  hexToRgb,
  hexToRgbAry,
  escapeEntity,
  unescapeEntity,
  getIdInfo,
}
